package com.huatai.bpmn.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.bpmn.commom.util.BaseCommService;
import com.huatai.bpmn.constant.PMPConstant;
import com.huatai.bpmn.entity.*;
import com.huatai.bpmn.entity.vo.UserTaskVo;
import com.huatai.bpmn.entity.vo.YYBasicEntityVo;
import com.huatai.bpmn.mapper.BasicDataMapper;
import com.huatai.bpmn.service.*;
import com.huatai.common.util.BeanUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import com.huatai.user.dubbo.UserDubboApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 审核通过之后存储的正式数据 服务实现类
 * </p>
 *
 * @author yxy
 * @since 2023-07-27
 */
@Service
public class BasicDataServiceImpl extends ServiceImpl<BasicDataMapper, BasicDataEntity> implements BasicDataService {

	@Autowired
	private YYFormService yyFormService;
	@Autowired
	private DicService dicService;
	@DubboReference(timeout = 30000, check = false, retries = 0)
	private UserDubboApi userDubboApi;
	@Autowired
	private BaseCommService baseCommService;
	@Autowired
	private BasicLoadService basicLoadService;
	@Autowired
	private YYBasicService yyBasicService;
	@Autowired
	private YYDataInfoService yyDataInfoService;
	@Autowired
	private YYExternalParameterService yyExternalParameterService;
	@Autowired
	private DeployFormMappingService deployFormMappingService;
	@Autowired
	private YYKeyHistoryService yyKeyHistoryService;
	@Autowired
	private InvestCapitalService investCapitalService;

	@Override
	public BasicDataEntity findByMykeyAndFlowId(String myKey,String businessKey) {
		BasicDataEntity basicDataEntity = this.getOne(Wrappers.<BasicDataEntity>lambdaQuery().eq(BasicDataEntity::getMyKey,myKey)
			.eq(BasicDataEntity::getFlowId, businessKey).eq(BasicDataEntity::getStatus, PMPConstant.STATUS_1));
		return basicDataEntity;
	}

	@Override
	public HashMap<String, Object> getInfo(String myKey, String businessKey) {
		HashMap<String, Object> dataMap = new HashMap<>();
		//实施的流程数据不同，如果遇到则直接处理掉
		if (myKey.equals(PMPConstant.TABLE_SJ_TQ_INFO)){
			InvestCapitalEntity capitalEntity = investCapitalService.getById(businessKey);
			dataMap.put("data", capitalEntity);
			return dataMap;
		}
		BasicDataEntity basicData = this.getOne(Wrappers.<BasicDataEntity>lambdaQuery().eq(BasicDataEntity::getMyKey,myKey)
				.eq(BasicDataEntity::getFlowId, businessKey).eq(BasicDataEntity::getStatus, PMPConstant.STATUS_1));
		HashMap<String, Object> paramMap = new HashMap<>();//存储表头和外部参数
		DeployFormMappingEntity deployFormMappingEntity = deployFormMappingService.getByMyKey(myKey);

		String externalParameterId = deployFormMappingEntity.getExternalParameterId();
		//获取项目表单配置
		YYExternalParameterEntity externalParameterEntity = yyExternalParameterService.getById(externalParameterId);
		if (ObjectUtil.isEmpty(externalParameterEntity)) {
			throw new RuntimeException("外部参数id错误");
		}
		String[] placeArr = getStrings(externalParameterEntity.getTableInfo());
		String place = externalParameterEntity.getPlace();

		HashMap<String, HashMap<String, Object>> map = new HashMap<>();//存储表头
		Arrays.stream(placeArr).forEach(table -> {
			//获取表单表头
			List<YYBasicEntity> colum = yyBasicService.getColum(table);
			ArrayList<YYBasicEntityVo> list = new ArrayList<>();
			for (YYBasicEntity yyBasicEntity : colum) {
				String jsonKey = yyBasicEntity.getJsonKey();
				//归口部门
				if (jsonKey.equals("gkbm")) {
					List<cn.hutool.json.JSONObject> childrenList = userDubboApi.getDepartList();
					YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
					BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
					yyBasicEntityVo.setChildren(childrenList);
					list.add(yyBasicEntityVo);
					continue;
				}

				YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
				BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
				if (!StringUtil.isEmpty(yyBasicEntity.getSelectItem())) {
					List<cn.hutool.json.JSONObject> childrenList = dicService.findChildrenData(yyBasicEntity.getSelectItem());
					yyBasicEntityVo.setChildren(childrenList);
				}
				list.add(yyBasicEntityVo);

			}
			YYFormEntity formEntity = yyFormService.getByPlace(table);

			dataMap.put("colum", list);
			dataMap.put("name", formEntity.getName());
			dataMap.put("allowChange", true);

			map.put(table, dataMap);
		});
		List<YYBasicEntity> colum = yyBasicService.getColum(place);
		ArrayList<YYBasicEntityVo> list = new ArrayList<>();
		for (YYBasicEntity yyBasicEntity : colum) {
			String jsonKey = yyBasicEntity.getJsonKey();
			//归口部门
			if (jsonKey.equals("gkbm")) {
				List<cn.hutool.json.JSONObject> childrenList = userDubboApi.getDepartList();
				YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
				BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
				yyBasicEntityVo.setChildren(childrenList);
				list.add(yyBasicEntityVo);
				continue;
			}
			DicEntity dicEntity = dicService.getCode(jsonKey);
			YYBasicEntityVo yyBasicEntityVo = new YYBasicEntityVo();
			BeanUtil.copy(yyBasicEntity, yyBasicEntityVo);
			if (!ObjectUtil.isEmpty(dicEntity)) {
				List<cn.hutool.json.JSONObject> childrenList = dicService.findChildrenData(dicEntity.getId());
				yyBasicEntityVo.setChildren(childrenList);
			}
			list.add(yyBasicEntityVo);
		}
		String param = basicData.getParam();
		JSONObject jsonObject = JSONObject.parseObject(param);
		//临时数据
		HashMap<String,Object> map1 = JSONObject.parseObject(jsonObject.getOrDefault("param", "").toString(), HashMap.class);
		HashMap<String,Object> map2 = JSONObject.parseObject(jsonObject.getOrDefault("data", "").toString(), HashMap.class);
		//原数据
		HashMap<String, Object> basicLoadServiceInfo = basicLoadService.getInfo(myKey, businessKey);
		HashMap<String,Object> map3 = JSONObject.parseObject(basicLoadServiceInfo.get("paramData").toString(),HashMap.class);
		//去掉自动计算的值
		HashMap<String,Object> map4 = JSONObject.parseObject(basicLoadServiceInfo.get("columnData").toString(),HashMap.class);
		HashMap<String, String> changeMap = new HashMap<>();
		//比较，对于不同的值需要存储
		Set<String> strings1 = map1.keySet();
		strings1.forEach(y->{
			//自动计算的值跳过
			if (y.equals(PMPConstant.KEY_YJMl)||y.equals(PMPConstant.KEY_YJMlL)){
				return;
			}
			//去掉遗留的值
			if (y.equals(PMPConstant.KEY_YJYS)){
				return;
			}
			YYBasicEntity yyBasicEntity = yyBasicService.getByJsonKey(y);
			if (ObjectUtil.isEmpty(yyBasicEntity)){
				return;
			}

			String str1 = map1.getOrDefault(y,"0").toString();
			String str2 = map3.getOrDefault(y,"").toString();
			if (!"0".equals(str1)&&!str1.equals(str2)){
				changeMap.put(yyBasicEntity.getJsonValue(),str1);
			}
		});
		Set<String> strings2 = map2.keySet();
		strings2.forEach(y->{
			String str1 = map2.getOrDefault(y,"").toString();
			String str2 = map4.getOrDefault(y,"").toString();
			if (!str1.equals(str2)){
				changeMap.put(y,str1);
			}
		});
		//查询值的历史变化
//		List<YYKeyHistoryEntity> keyList = yyKeyHistoryService.list(Wrappers.<YYKeyHistoryEntity>lambdaQuery().eq(YYKeyHistoryEntity::getBusinessKey, businessKey));
		List<JSONObject> keyList = yyKeyHistoryService.listByBusinessKey(businessKey);
		paramMap.put("history", keyList);
		paramMap.put("param", list);
		paramMap.put("column", map);
		paramMap.put("paramData", jsonObject.getOrDefault("param",""));
		paramMap.put("columnData", jsonObject.getOrDefault("data",""));
		paramMap.put("changeMap", changeMap);
		return paramMap;
	}

	@Override
	public List<UserTaskVo> listByUserId(Long userId) {
		return this.getBaseMapper().listByUserId(userId);
	}



    private String[] getStrings(String arrStr) {
		if (StringUtil.isEmpty(arrStr)) {
			return new String[]{};
		}
		return arrStr.split(",");
	}
	/**
	 *查询实施人工天的所有未完成审核的项目
	 * @param myKey
	 * @return
	 */
	@Override
	public List<BasicDataEntity> listByMyKey(String myKey) {
		return this.list(Wrappers.<BasicDataEntity>lambdaQuery().eq(BasicDataEntity::getMyKey,myKey).eq(BasicDataEntity::getStatus,PMPConstant.STATUS_1));
	}

	@Override
	public BasicDataEntity getByFlowIdAndStatus(Long flowId) {
		return this.getOne(Wrappers.<BasicDataEntity>lambdaQuery().eq(BasicDataEntity::getFlowId,flowId).eq(BasicDataEntity::getStatus,PMPConstant.STATUS_1));
	}
}
